package rjgc.mall.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.sql.*;

@Configuration
public class DatabaseInitConfig {
    private static final Logger LOG = LoggerFactory.getLogger(DatabaseInitConfig.class);

    private static final String SCHEMA_NAME = "schema_name";

    private static final String DATABASE_NAME = "mall";

    /**
     * com.mysql.cj.jdbc.Driver
     */
    @Value("${spring.datasource.driver-class-name}")
    private String driver;
    /**
     * jdbc_url
     */
    @Value("${spring.datasource.url}")
    private String url;
    /**
     * 账号名称
     */
    @Value("${spring.datasource.username}")
    private String username;
    /**
     * 账号密码
     */
    @Value("${spring.datasource.password}")
    private String password;
    /**
     * 需要创建的数据名称
     */

    @PostConstruct
    public void init() {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException  e) {
            LOG.error("JDBC URL解析错误", e);
        }

        try (
                Connection connection = DriverManager.getConnection(url, username, password);
                Statement statement = connection.createStatement()) {
            String sal = "select schema_name from information_schema.schemata where schema_name = " + "'" + DATABASE_NAME + "'";

            //查询返回的结果集
            ResultSet resultSet = statement.executeQuery(sal);
            if (!resultSet.next()) {
                //查不到数据库，执行数据库初始化脚本
                LOG.warn("查不到数据库({})", DATABASE_NAME);
                String createDb = "CREATE DATABASE IF NOT EXISTS " + DATABASE_NAME
                        + " DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci ";
                connection.setAutoCommit(false);
                statement.execute(createDb);
                connection.commit();
                LOG.info("创建数据库（{}）成功", DATABASE_NAME);
            } else {
                String databaseName = resultSet.getString(SCHEMA_NAME);
                LOG.warn("已经存在数据库({})", databaseName);
            }
            if (resultSet.isClosed()) {
                resultSet.close();
            }
        } catch (SQLException e) {
            LOG.error("启动项目检查数据库是否创建报错", e);
        }

    }

}
